//
//  SJHomeViewController.m
//  YYPHSpeedJump
//
//  Created by sujiang on 15/12/16.
//  Copyright © 2015年 sujiang. All rights reserved.
//

#import "SJHomeViewController.h"
#import "SJDetailViewController.h"
#import "HistoryViewController.h"
#import "AlertV.h"
#import "ReChargeViewController.h"
#import "SJHomeCell.h"
#import "HelpViewController.h"
#import "SJHomeHeaderView.h"
#import "MyIntegral.h"
#import "PicTextViewController.h"

@interface SJHomeViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
{
    UIView *baseView;
    AlertV *tipsView;
    NSString *join_by;
    NSInteger page;
    NSDateFormatter *formatter;
    NSTimeInterval deviation;
}
@property (nonatomic, strong) NSTimer *timeTimer;
@property (nonatomic, assign) NSInteger second;
@property (nonatomic, strong) NSTimer *priceTimer;
@property (nonatomic, assign) CGFloat price;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *paths;
@property (nonatomic, assign) CGFloat remain_jump_time;
@property (nonatomic, strong) NSMutableArray *loopImages;

@end

@implementation SJHomeViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;

}

- (NSMutableArray *)loopImages
{
    if (!_loopImages) {
        _loopImages = [NSMutableArray array];
    }
    return _loopImages;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)paths
{
    if (!_paths) {
        _paths = [NSMutableArray array];
    }
    return _paths;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"速降";
    formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
    page = 1;
    _second = 0;
    [self addSubViews];
    [self requestData];
    [NSThread detachNewThreadSelector:@selector(startTime) toTarget:self withObject:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(actionEnterForeground) name:@"EnterForeground" object:nil];
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"newRegist"])
    {
        [Tools showAlert:@"您是新注册用户,请先前往个人完善个人资料,以免耽误您的付款时间!"];
        [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"newRegist"];
    }
}

- (void)actionEnterForeground
{
    [self requestData];
}

- (void)requestData
{
    _second = 0;
    _price = 0;
    
    // app.do?cmd=main_page_head
    NSString *url = [NSString stringWithFormat:@"%@/app.do?cmd=main_page_head", kBaseUrl];
    [NetworkHandle getInfoWithUrl:url dictionary:nil success:^(NSDictionary *dictionary) {
        self.loopImages = [NSMutableArray arrayWithArray:dictionary[@"data"]];
    }];
    NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, kSJHomeUrl];
    [NetworkHandle getUpDataWithUrl:string class:NSClassFromString(@"SJHomeModel") dictionary:nil firstKey:@"data" secondKey:@"next_period_list" success:^(NSArray *array) {
        if (page == 1) {
            [self.dataArray removeAllObjects];
        }
        BOOL isJumping = NO;
        [self.dataArray addObjectsFromArray:array];
        for (SJHomeModel *model in self.dataArray) {
            if (model.status.integerValue == 2) {
                isJumping = YES;
                NSDate *currDate = [formatter dateFromString:model.current_time];
                NSDate *endDate = [formatter dateFromString:model.end_time];
                NSTimeInterval currtime = [currDate timeIntervalSince1970];
                NSTimeInterval endtime = [endDate timeIntervalSince1970];
                NSDate *startD = [formatter dateFromString:model.start_time];
                NSTimeInterval start = [startD timeIntervalSince1970];
                NSDate *nowD = [NSDate date];
                NSTimeInterval now = [nowD timeIntervalSince1970];
                deviation = now - currtime; // 误差时间
                model.remain_time = endtime - currtime;
                _price = model.original_price.floatValue * (endtime - currtime) / (endtime - start);
                model.percent = _price / model.original_price.floatValue;
                [self performSelectorInBackground:@selector(timerFire:) withObject:model];
            } else {
                NSDate *currDate = [formatter dateFromString:model.current_time];
                NSDate *startDate = [formatter dateFromString:model.start_time];
                NSTimeInterval currtime = [currDate timeIntervalSince1970];
                NSTimeInterval strattime = [startDate timeIntervalSince1970];
                model.remain_time = strattime - currtime;
                model.percent = 1.0f;
            }
        }
        if (!isJumping) {
            [self.priceTimer invalidate];
        }
        [self.collectionView.header endRefreshing];
        [self.collectionView reloadData];
    }];
}

- (void)addSubViews
{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.sectionInset = UIEdgeInsetsMake(5, 13, 5, 13);
    layout.itemSize = CGSizeMake((kScreenWidth - 35) / 2, 162);
    layout.minimumLineSpacing = 10;
    layout.minimumInteritemSpacing = 5;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) collectionViewLayout:layout];
    [self.view addSubview:self.collectionView];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = kColors(231, 231, 231, 1);
    [self.collectionView registerNib:[UINib nibWithNibName:@"SJHomeCell" bundle:nil] forCellWithReuseIdentifier:@"SJHomeCell"];
    [self.collectionView registerClass:NSClassFromString(@"SJHomeHeaderView") forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SJHomeHeaderView"];
    
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
}
#pragma mark -- 下拉刷新
- (void)headerRefresh
{
    page = 1;
    [self requestData];
}

#pragma mark -- collectionView 代理方法

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.dataArray.count > 0) {
        return self.dataArray.count;
    } else {
        return 0;
    }
}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    SJHomeCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SJHomeCell" forIndexPath:indexPath];
    SJHomeModel *model = self.dataArray[indexPath.row];
    [cell.goodImageView sd_setImageWithURL:[NSURL URLWithString:model.head_img_url] placeholderImage:[UIImage imageNamed:@"tu-zhong02"]];
    cell.model = model;
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]){
        SJHomeHeaderView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"SJHomeHeaderView" forIndexPath:indexPath];
        [headView.historyBtn addTarget:self action:@selector(actionSeeHistory) forControlEvents:(UIControlEventTouchUpInside)];
        [headView.direction addTarget:self action:@selector(actionSeeDirection) forControlEvents:(UIControlEventTouchUpInside)];
        [headView.intergral addTarget:self action:@selector(actionSeeIntergral) forControlEvents:(UIControlEventTouchUpInside)];
        headView.cycScroll.imageURLStringsGroup = self.loopImages;
        return headView;
    }
    return nil;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return CGSizeMake(kScreenWidth, 248);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SJHomeModel *model = self.dataArray[indexPath.row];
    if (model.status.integerValue == 1) {
        PicTextViewController *VC = [[PicTextViewController alloc] init];
        VC.webUrl = model.detail_url;
        self.tabBarController.tabBar.hidden = YES;
        [self.navigationController pushViewController:VC animated:YES];
        return;
    }
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"logined"]) {
        [Tools showAlert:@"您还未登录,请到个人登录!"];
        return;
    }
    NSString *string = [NSString stringWithFormat:@"%@%@", kBaseUrl, kCheckUrl];
    NSDictionary *dict = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"period_id":model.period_id};
        [NetworkHandle addToWindow];
    [NetworkHandle getInfoWithUrl:string dictionary:dict success:^(NSDictionary *dictionary) {
        [NetworkHandle removeFromWindow];
        if ([dictionary[@"code"] integerValue] == 2700) {
            [Tools showAlert:dictionary[@"message"]];
            [self requestData];
            return;
        }
        [self PushToNextVCWith];
    }];
}

- (void)PushToNextVCWith
{
    SJDetailViewController *detailVC = [[SJDetailViewController alloc] init];
    [self.navigationController pushViewController:detailVC animated:YES];
    self.navigationController.hidesBottomBarWhenPushed = YES;
    self.tabBarController.tabBar.hidden = YES;
    SJHomeModel *model = self.dataArray[0];
    detailVC.leftTime = model.remain_time;
    detailVC.deviation = deviation;
    detailVC.price= _price;
    detailVC.model = model;
    SJHomeCell *cell = (SJHomeCell *)[self.collectionView cellForItemAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
    detailVC.image = cell.goodImageView.image;
    detailVC.endblock = ^(BOOL end){
        if (end) {
            //[self.timeTimer invalidate];
            //[self.priceTimer invalidate];
            [self requestData];
        }
    };
}

#pragma mark -- 点击事件

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        SJHomeModel *model = self.dataArray[0];
       NSString *url = [NSString stringWithFormat:@"%@%@", kBaseUrl, kJoinUrl];
        NSDictionary *dic1 = @{@"u":[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"], @"period_id":model.period_id, @"join_by":join_by};
        [NetworkHandle getInfoWithUrl:url dictionary:dic1 success:^(NSDictionary *dictionary) {
            if ([dictionary[@"code"] integerValue] == 200) {
                [self PushToNextVCWith];
                NSDictionary *dicti = dictionary[@"current"];
                [model setValuesForKeysWithDictionary:dicti];
            } else {
                [Tools showAlert:dictionary[@"message"]];
            }
        }];
    }
}

- (void)gotoChongZhi:(UIButton *)button
{
    [tipsView removeFromSuperview];
    [baseView removeFromSuperview];
    ReChargeViewController *rechVC = [[ReChargeViewController alloc] initWithNibName:@"ReChargeViewController" bundle:nil];
    [self.navigationController pushViewController:rechVC animated:YES];
}

- (void)ignore:(UIButton *)button
{
    [tipsView removeFromSuperview];
    [baseView removeFromSuperview];
    if (button.tag == 999) {
        return;
    }
    [self PushToNextVCWith];
}


// 查看速降历史
- (void)actionSeeHistory
{
    HistoryViewController *historyVC = [[HistoryViewController alloc] init];
    [self.navigationController pushViewController:historyVC animated:YES];
    self.navigationController.hidesBottomBarWhenPushed = YES;
    self.tabBarController.tabBar.hidden = YES;
}

// 新手指南
- (void)actionSeeDirection
{
    HelpViewController *helpVC =[[HelpViewController alloc] init];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:helpVC animated:YES];
}
// 查看积分任务
- (void)actionSeeIntergral
{
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"logined"]) {
        [Tools showAlert:@"您还未登录,请到个人登录!"];
        return;
    }

    MyIntegral *intergralVC = [[MyIntegral alloc] init];
    [self.navigationController pushViewController:intergralVC animated:YES];
    self.tabBarController.tabBar.hidden = YES;
    
}

#pragma mark -- 处理价格变化

- (void)timerFire:(SJHomeModel *)model
{
    if (model.status.integerValue == 2) {
        [self.priceTimer invalidate];
        self.priceTimer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(actionChangePrice:) userInfo:model repeats:YES];
    }
    [[NSRunLoop currentRunLoop] run];
}

- (void)actionChangePrice:(NSTimer *)timer
{
    SJHomeModel *model = self.dataArray[0];
    if (self.price <= 0.0) {
        self.price = 0.0;
        [self.priceTimer invalidate];
        model.current_price = [NSString stringWithFormat:@"%.1f", _price];
        return;
    }
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSTimeInterval start = [[formatter dateFromString:model.start_time] timeIntervalSince1970];
    NSDate *endDate = [formatter dateFromString:model.end_time];
    NSTimeInterval end = [endDate timeIntervalSince1970] - deviation;
    self.price = model.original_price.floatValue * (end - now) / (end - start);
    model.current_price = [NSString stringWithFormat:@"%.1f", _price];
}

- (void)setPrice:(CGFloat)price
{
    _price = price;
    [self performSelectorOnMainThread:@selector(handleWithPrice) withObject:nil waitUntilDone:YES];
}

- (void)handleWithPrice
{
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:0];
    SJHomeCell *cell = (SJHomeCell *)[self.collectionView cellForItemAtIndexPath:index];
    SJHomeModel *model = self.dataArray[index.row];
    cell.model = model;
}

#pragma mark -- 处理倒计时变化

- (void)startTime
{
    self.timeTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(actionChangeTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
}

- (void)actionChangeTimer
{
    for (SJHomeModel *model in self.dataArray) {
        if (model.status.integerValue != 2) {
            model.remain_time -= 1.0f;
        }
    }
    self.second += 1.0f;
}

- (void)setSecond:(NSInteger)second
{
    _second = second;
    [self performSelectorOnMainThread:@selector(handleWithLeftTime) withObject:nil waitUntilDone:YES];
}

- (void)handleWithLeftTime
{
    for (SJHomeModel *model in self.dataArray) {
        if (model.remain_time <= 0) {
            [self requestData];
            return;
        }
    }
    for (int i = 0; i < self.dataArray.count; i++) {
        NSIndexPath *path = [NSIndexPath indexPathForRow:i inSection:0];
        SJHomeCell *cell = (SJHomeCell *)[self.collectionView cellForItemAtIndexPath:path];
        SJHomeModel *model = self.dataArray[i];
        NSString *hour = [NSString stringWithFormat:@"%.2ld", model.remain_time / 60 / 60];
        NSString *min = [NSString stringWithFormat:@"%.2ld", (model.remain_time % 3600) / 60];
        NSString *sec = [NSString stringWithFormat:@"%.2ld", model.remain_time % 60];
        cell.timeLb.text = [NSString stringWithFormat:@"%@:%@:%@", hour, min, sec];
    }
}



@end
